package com.ahao.aggregation.utils;

import android.os.AsyncTask;

import com.ahao.aggregation.entry.UserInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SimpleHttpGetRequest extends AsyncTask<Object, Void, String> {

    private OnHttpRequestCompleteListener listener;

    public static String HOST = "";
    public static String extParams = "";

    public interface OnHttpRequestCompleteListener {
        void onHttpRequestComplete(String result);
    }

    public static String handleParams(Object params) {
        if (params == null || params.equals("")) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        Field[] fields = params.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);

            try {
                Object value = field.get(params);

                if (value != null) {
                    if (result.length() > 0) {
                        result.append("&");
                    }

                    result.append(URLEncoder.encode(field.getName(), "UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode(value.toString(), "UTF-8"));
                }
            } catch (IllegalAccessException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return result.toString();
    }

    public SimpleHttpGetRequest(OnHttpRequestCompleteListener listener) {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(Object... urls) {
        if (urls.length == 0) {
            return null;
        }

        try {
            String urlString = HOST + urls[0];
            String params = "";
            if (urls.length > 1) {
                params = handleParams(urls[1]);
            }
            String token = "";
            if (UserInfo.getInstance().getLoginResult()!=null) {
                token = UserInfo.getInstance().getLoginResult().getToken();
                // 将token进行url编码
                token = URLEncoder.encode(token, "UTF-8");
            }
            urlString = (urlString.contains("?") ? urlString + "&" : urlString + "?") + params  + extParams;
            if (urlString.contains("?") && !urlString.contains("token")) {
                urlString = urlString + "&token=" + token;
            } else {
                urlString = urlString + "?token=" + token;
            }
            LogUtils.info("request " + urlString);

            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            try {
                InputStream in = urlConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line).append("\n");
                }

                return result.toString();
            } finally {
                urlConnection.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {
        LogUtils.info("response " + result);
        if (listener != null) {
            listener.onHttpRequestComplete(result);
        }
    }
}
